package com.examination.mlib.view;

import static com.examination.mlib.utils.SchemeUtil.HOST_CMS;
import static com.examination.mlib.utils.SchemeUtil.HOST_URL;

import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.bumptech.glide.Glide;
import com.examination.mlib.R;
import com.examination.mlib.constants.UserInfoConstants;
import com.google.gson.Gson;
import com.examination.mlib.bean.PromoteSourceV0;
import com.examination.mlib.interfaceapi.NetWorkCallBack;
import com.examination.mlib.utils.SchemeUtil;
import com.yilijk.base.network.RequestParams;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.network.https.interceptor.NetWorkUtils;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.CommonUtils;
import com.yilijk.base.utils.DevicesUtils;
import com.yilijk.base.utils.ScreenUtils;
import com.yilijk.base.utils.SharedPreferencesUtils;
import com.yilijk.base.utils.UIUtils;

import org.json.JSONObject;

/**
 * 双十一活动 - 定时限量发放大面额问诊券  悬浮球
 */
public class SuspendedBallView extends FrameLayout {

    private final int showDuration = 3 * 1000;

    private static int MAX_TOP = 300;

    private Context context;
    private View contentView;
    private ImageView gitIv;
    private Animation hideAnim;
    private Animation showAnim;
    private Handler handler;
    private Runnable hideRunnable;
    private String activityUrl;
    private boolean isClickShow = false;
    private int screenWidth, screenHeight;
    private int mainTabH = 0;

    public SuspendedBallView(Context context) {
        super(context);
        init(context);
    }

    public SuspendedBallView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public SuspendedBallView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public SuspendedBallView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context);
    }

    private boolean clickormove = true;  //点击或拖动，点击为true，拖动为false
    private int downX, downY;   //按下时的X，Y坐标
    private int lastX, lastY;    //保存手指点下的点的坐标
    private int lastLeft, lastTop;    //记录上次滑动的左边距和上边距

    int ballH, ballW, ballL, ballT;

    private void init(Context context) {

        this.context = context;
        contentView = LayoutInflater.from(context).inflate(R.layout.view_suspended_ball, this);
        gitIv = contentView.findViewById(R.id.iv_gif);
//        GlideUtil.loadGif(context, R.drawable.icon_default_square, gitIv);
        screenHeight = ScreenUtils.getScreenHeight();
        screenWidth = ScreenUtils.getScreenWidth();
        mainTabH = ScreenUtils.dip2px(context, 70);
        handler = new Handler();
        hideRunnable = new Runnable() {
            @Override
            public void run() {
//                hide();
            }
        };
        show();

        setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        lastX = (int) event.getRawX();
                        lastY = (int) event.getRawY();
                        ballH = getHeight();
                        ballW = getWidth();
                        ballL = getLeft();
                        ballT = screenHeight - ballH - mainTabH;
                        downX = lastX;
                        downY = lastY;
                        break;
                    case MotionEvent.ACTION_MOVE:
                        //计算出需要移动的距离
                        int dx = (int) event.getRawX() - lastX;
                        int dy = (int) event.getRawY() - lastY;
                        //将移动距离加上，现在本身距离边框的位置
                        int left = getLeft() + dx;
                        int top = getTop() + dy;
                        int right = getRight() + dx;
                        int bottom = getBottom() + dy;
                        if (left < 0) {
                            left = 0;
                            right = left + getWidth();
                        }
                        if (right > screenWidth) {
                            right = screenWidth;
                            left = right - getWidth();
                        }
//                        if (top < 0) {
//                            bottom = top + getHeight();
//                        }
                        if (top > ballT) {
                            top = ballT;
//                            bottom = top + getHeight();
                        }
                        //获取到layoutParams然后改变属性，在设置回去
                        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) getLayoutParams();
                        layoutParams.gravity = 0;
                        layoutParams.height = ballH;
                        layoutParams.width = ballW;

                        layoutParams.leftMargin = left;
                        layoutParams.topMargin = top;
                        setLayoutParams(layoutParams);
                        lastX = (int) event.getRawX();
                        lastY = (int) event.getRawY();
                        lastTop = top;
                        lastLeft = left;
                        break;
                    case MotionEvent.ACTION_UP:
                        //判断是单击事件或是拖动事件，位移量大于5则断定为拖动事件
                        if (Math.abs((int) (event.getRawX() - downX)) > 5 || Math.abs((int) (event.getRawY() - downY)) > 5) {
                            clickormove = false;
                            FrameLayout.LayoutParams layoutParams1 = (FrameLayout.LayoutParams) getLayoutParams();
                            layoutParams1.gravity = 0;
                            layoutParams1.height = ballH;
                            layoutParams1.width = ballW;

                            if (lastTop < MAX_TOP) {
                                layoutParams1.topMargin = MAX_TOP;
                            } else {
                                layoutParams1.topMargin = lastTop;
                            }
                            if (lastLeft < (int) (screenWidth * 0.5)) {
                                layoutParams1.leftMargin = 0;
                            } else {
                                layoutParams1.leftMargin = screenWidth - ballW;
                            }
                            setLayoutParams(layoutParams1);
//                            }
                        } else {
                            clickormove = true;
                        }
                        break;
                }
                postInvalidate();
                return false;
            }
        });
    }

    public void hide() {
        isClickShow = false;
        if (hideAnim == null) {
            hideAnim = AnimationUtils.loadAnimation(context, R.anim.hide_supended_ball);
        }
        contentView.startAnimation(hideAnim);

    }

    public void show() {
        if (!clickormove) {
            return;
        }
        if (isClickShow) {
            /**
             * 展开状态下二次点击事件跳转处理
             */
            ALog.i("展开状态下二次点击事件跳转处理", "show & click listener: " + activityUrl);
//            activityUrl = "/com.patient.scheme:cms?load=112";
            if (!TextUtils.isEmpty(activityUrl)) {
                if (activityUrl.startsWith("http") || activityUrl.startsWith("https")) {
                    SchemeUtil.navigation(context, SchemeUtil.SCHEME + "://" + HOST_URL + "?load=" + activityUrl);
                } else {
//                    Uri uri = Uri.parse("/submy/cmsModule/main?promotionId=112");
//                    /com.doctor.scheme:cms?load=112
//                    /com.doctor.scheme:cms?load=114
//                    /submy/cmsModule/main?promotionId=110
                    String promotionId = "";
                    if (activityUrl.contains("com.patient.scheme:cms?load=")) {
                        promotionId = activityUrl.split("load=")[1];
                    } else if (activityUrl.contains("com.doctor.scheme:cms?load=")) {
                        promotionId = activityUrl.split("load=")[1];
                    } else if (activityUrl.contains("com.patient.scheme:url?load=")) {
                        String load = activityUrl.split("load=")[1];
                        if (load.startsWith("http") || load.startsWith("https")) {
                            SchemeUtil.navigation(context, SchemeUtil.SCHEME + "://" + HOST_URL + "?load=" + load);
                            return;
                        } else {
                            promotionId = load;
                        }
                    } else if (activityUrl.contains("com.doctor.scheme:url?load=")) {
                        String load = activityUrl.split("load=")[1];
                        if (load.startsWith("http") || load.startsWith("https")) {
                            SchemeUtil.navigation(context, SchemeUtil.SCHEME + "://" + HOST_URL + "?load=" + load);
                            return;
                        } else {
                            promotionId = load;
                        }
                    } else {
                        try {
                            Uri uri = Uri.parse(activityUrl);
                            if ("/submy/cmsModule/main".equals(uri.getPath())) {
                                promotionId = uri.getQueryParameter("promotionId");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    ALog.e("okhttp:", "promotion id: " + promotionId);
                    if (!TextUtils.isEmpty(promotionId)) {
                        SchemeUtil.navigation(context, SchemeUtil.SCHEME + "://" + HOST_CMS + "?load=" + promotionId);
                    }


                }
            }

            return;
        } else {
            isClickShow = true;
        }
        if (hideAnim != null) {
            hideAnim.cancel();
        }
        if (showAnim == null) {
            showAnim = AnimationUtils.loadAnimation(context, R.anim.show_supendend_ball);
            showAnim.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                    ALog.e("oakkk", "alpha start: " + contentView.getAlpha());
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    ALog.e("oakkk", "alpha end: " + contentView.getAlpha());
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
        }
        contentView.startAnimation(showAnim);
        handler.removeCallbacks(hideRunnable);
        handler.postDelayed(hideRunnable, showDuration);

    }

    /**
     * 设置悬浮球Icon
     *
     * @param url
     */
    public void setGifIcon(String url) {
        if (gitIv == null) {
            ALog.e(getClass().getSimpleName().toString(), "gitIv is null");
        } else if (TextUtils.isEmpty(url)) {
            ALog.e(getClass().getSimpleName().toString(), "url is null");
        } else {
            Glide.with(this)
                    .load(url)
                    .error(R.drawable.icon_default_square)
                    .into(gitIv);
        }
    }

    /**
     * 设置悬浮球Icon
     *
     * @param icon
     */
    public void setGifIcon(int icon) {
        if (gitIv == null) {
            ALog.e(getClass().getSimpleName().toString(), "gitIv is null");
        } else if (icon == 0) {
            ALog.e(getClass().getSimpleName().toString(), "icon is 0");
        } else {
            Glide.with(this)
                    .load(icon)
                    .error(R.drawable.icon_default_square)
                    .into(gitIv);
        }
    }

    /**
     * 设置悬浮球点击Url
     *
     * @param activityUrl
     */
    public void setActivityUrl(String activityUrl) {
        this.activityUrl = activityUrl;
    }

    /**
     * created by SHICHENG
     * 2021/10/23
     * hidder() 是否隐藏悬浮球
     * setIcon(String iconUrl) iconUrl 悬浮球Icon图标Url
     * getUrl(String url) url 悬浮球活动地址Url
     */
    public interface HiddenCallBack {
        void hidden(boolean hidden);

        void setIcon(String iconUrl);

        void getUrl(String url);
    }

    /**
     * 悬浮球接口
     * https://api.d1.yilijk.com/apivbp/api/patient/promotion/getPromoteResource
     * sessUid（passportId）
     * location 1、首页 2、消息 3、我的
     *
     * @param hiddenCallBack
     */
    public void isHiddenSuspendedBallView(int location, SuspendedBallView.HiddenCallBack hiddenCallBack) {
        String sessUid = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.account_passportId, "0");
        RequestParams params = new RequestParams();
        params.put("sessUid",sessUid);
        params.put("location",location+"");
        HttpUtils.get("/apivbp/api/patient/promotion/getPromoteResource", params,new HttpCallBack<PromoteSourceV0>() {

            @Override
            public void onSuccess(PromoteSourceV0 promoteSourceV0, int i) {
                PromoteSourceV0.DataBean data = promoteSourceV0.getData();
                if (data.isShowFloatIcon()) {
                    hiddenCallBack.hidden(false);
                    setVisibility(VISIBLE);
                    gitIv.setVisibility(VISIBLE);
                    postInvalidate();
                } else {
                    hiddenCallBack.hidden(true);
                    setVisibility(GONE);
                    gitIv.setVisibility(GONE);
                    postInvalidate();
                    return;
                }

                if (!TextUtils.isEmpty(data.getFloatIcon())) {
                    hiddenCallBack.setIcon(data.getFloatIcon());
//                            hiddenCallBack.setIcon("https://cdn.yilijk.com/images/vbp/patientimg/ext/home-red.gif");
                } else {
                    hiddenCallBack.setIcon(null);
                }
                if (!TextUtils.isEmpty(data.getIconUrl())) {
                    hiddenCallBack.getUrl(data.getIconUrl());
                } else {
                    hiddenCallBack.getUrl(null);
                }

            }

            @Override
            public void onFailure(String s, int i) {
                hiddenCallBack.hidden(true);
            }
        });
    }


}
